<template>
  <div style="display: flex; height: 100%; flex: 1;">
    <HierarchyList :pagination="pagination" :columns="columns" :load-data="loadData"
                   ref="refHiUser" :search-form="searchItems" :create-label="props.createLabel"
                   :add-item="addUser"/>
    <EditDialog ref="refEditDlg" :columns="columns" :rules="rules" :submit="onSubmit"
                :form-label-width="100" :is-show-dialog="false"/>
  </div>
</template>

<script setup lang="ts">

import {onMounted, ref} from "vue";

import {buildSearchForms} from "@/data/PageData";
import {msgError, msgInfo} from "@/utils/InfoUtil";
import {useCurrent} from "@/utils/UseCurrentFunc";
import EditDialog from "@/components/common/EditDialog.vue";
import HierarchyList from "@/widget/list/HierarchyList.vue";
import {TYPES} from "@/stores/conf";
import {getStateOptions, getStateTag, getStateText, handleResult} from "@/utils/SystemUtil";
import {useStore} from "@/stores";
import {resetUserPassword, updateUserCache} from "@/apis";

const props = withDefaults(defineProps<{
  entry: any,
  product?: boolean,
  loadUser?: any,
  saveUser?: any,
  canEdit?: boolean,
  createLabel?: string,
}>(), {
  canEdit: true,
  createLabel: '增加用户',
});

const refHiUser = ref();
const refEditDlg = ref();

const currentItem = ref();
const searchItems = ref(buildSearchForms('用户', props.product, true));

const {updateCurrent} = useCurrent(props.entry.name);

const rules = ref({
  name: [{required: true, message: '请输入用户名称', trigger: ['blur', 'change']},],
  account: [{required: true, message: '请输入用户账号', trigger: ['blur', 'change']},],
})

const loadData = async (params: any) => {
  let result;

  if (props.loadUser) {
    result = await props.loadUser(params);
    if (result && result.code === 0) {
      handleResult(result.data, ['comment'])
      msgInfo('加载用户信息成功!');
    } else {
      msgError(result ? result.message : '加载用户信息失败！');
    }
  }

  return result;
}

const refresh = async () => {
  refHiUser.value?.refresh();
}

const removeUserCache = async (userId: string) => {
  const store = useStore();
  const result: any = await updateUserCache({
    userId: userId,
    realmId: store.getCurrentRealms().id || 'default'
  });

  if (result && result.code === 0) {
    msgInfo('删除用户缓存成功')
  } else {
    msgInfo(result?.message || '删除用户缓存失败');
  }
}

const resetRealmUserPassword = async (userId: string) => {
  const store = useStore();
  const result: any = await resetUserPassword({
    userId: userId,
    realmId: store.getCurrentRealms().id || 'default'
  });

  if (result && result.code === 0) {
    msgInfo('重置用户密码成功')
  } else {
    msgInfo(result?.message || '重置用户密码失败');
  }
}

const onSubmit = async (item: Record<string, any>, editType: string) => {
  if (props.saveUser) {
    console.log('--- create user', editType, item)
    if ('add' === editType) {
      if (item.account) {
        item.accounts = [{
          realmId: item.realmId,
          category: 'account',
          account: item.account,
          data: '',
        }]
      }
    }

    const result: any = await props.saveUser(item);

    if (result && result.code === 0) {
      msgInfo('保存用户信息成功!');
      setTimeout(() => refresh(),300);
    } else {
      msgError(result ? result.message : '保存用户信息失败！');
    }

    return result;
  }
}

const newUser = () => {
  return {
    state: 1,
    groupId: 'default',
    userType: 'default',
    type: TYPES.USER,
  };
}

const pagination = ref({
  current: 1,
  pageSize: 20,
  total: 0,
});

const columns = ref([
  {
    id: 'id',
    name: '标识',
    hideCol: true,
    show: false,
    canEdit: false,
  },
  {
    id: 'name',
    name: '用户名称',
    show: true,
    action: (data: any, row: any, index: number) => {
      updateCurrent({type: TYPES.USER, ...row})
    }
  },
  {
    id: 'account',
    name: '账号',
    show: false,
    canEdit: true,
  },
  {
    id: 'phone',
    name: '电话',
    show: true,
  },
  {
    id: 'state',
    name: '状态',
    show: true,
    tag: 'true',
    type: 'select',
    tagType: (tag: number) => {
      return getStateTag(tag);
    },
    tagText: (tag: number) => {
      return getStateText(tag);
    },
    options: getStateOptions(false, true)
  },
  {
    id: 'lastLoginTime',
    name: '最后一次登录',
    show: true,
    canEdit: false,
  },
  {
    id: 'createTime',
    name: '创建时间',
    show: true,
    canEdit: false,
  },
  {
    id: 'operation',
    name: '操作',
    show: true,
    canEdit: false,
    hideCol: true,
    fixed: 'right',
    operations: [
      {
        type: 'confirm',
        name: '重置密码',
        tips: () => {
          return '确定重置用户密码？'
        },
        iconType: 'primary',
        confirm: async (data: any, row: any) => {
          await resetRealmUserPassword(row.id);
        },
      },
      {
        type: 'confirm',
        name: '删除缓存',
        tips: () => {
          return '确定删除用户缓存？'
        },
        iconType: 'primary',
        confirm: async (data: any, row: any) => {
          await removeUserCache(row.id);
        },
      },
      {
        name: '编辑',
        callback: (data: any, row: any) => {
          currentItem.value = row;
          columns.value[2].canEdit = false
          refEditDlg.value?.editUpdate('编辑用户', row);
        }
      },
      {
        type: 'confirm',
        name: '删除',
        tips: () => {
          return '确定删除用户？'
        },
        confirm: async (data: any, row: any) => {
          row.state = 3;
          const result = await props.saveUser(row);
          if (result && result.code === 0) {
            await refresh();
          } else {
            msgError(result?.message || '删除用户异常');
          }
        },
        cancel: () => {
        }
      }
    ]
  }
]);

const addUser = () => {
  currentItem.value = newUser();
  columns.value[2].canEdit = true;
  columns.value[2].readOnly = false;
  refEditDlg.value?.editAdd('新增用户', currentItem.value);
}

onMounted(() => {
  if (!props.canEdit) {
    columns.value.pop();
  }
})

defineExpose({
  refresh,
})

</script>

<style scoped>
.el-form-item-class .el-form-item__label {
  font-size: 12px;
}

</style>
